const DEFAULT_SESSION_ENDPOINT = 'http://127.0.0.1:8766';
const TMPMAIL_BASE_URL = 'https://www.tmpmail.vip';
const TMPMAIL_DOMAIN_URL = `${TMPMAIL_BASE_URL}/user/api/domains`;
const TMPMAIL_MAILBOX_URL = `${TMPMAIL_BASE_URL}/user/api/mailboxes`;
const TMPMAIL_MAILS_URL = (mailboxId) => `${TMPMAIL_BASE_URL}/user/api/mailboxes/${mailboxId}/mails`;
const TMPMAIL_MAIL_DETAIL_URL = (mailId) => `${TMPMAIL_BASE_URL}/user/api/mails/${mailId}`;
const TMPMAIL_LOGIN_URL = `${TMPMAIL_BASE_URL}/user/api/login`;
const AUGMENT_REGISTER_URL = 'https://app.augmentcode.com/';
const TMPMAIL_HEADERS_BASE = {
  accept: '*/*',
  'accept-language': 'zh-CN,zh;q=0.9',
  'cache-control': 'no-cache',
  dnt: '1',
  pragma: 'no-cache',
  priority: 'u=1, i',
  referer: `${TMPMAIL_BASE_URL}/user/dashboard`,
  'sec-ch-ua': '"Chromium";v="142", "Google Chrome";v="142", "Not_A Brand";v="99"',
  'sec-ch-ua-mobile': '?0',
  'sec-ch-ua-platform': '"macOS"',
  'sec-fetch-dest': 'empty',
  'sec-fetch-mode': 'cors',
  'sec-fetch-site': 'same-origin',
  'user-agent':
    'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 96131',
};

class AutoFillManager {
  constructor() {
    this.currentTabId = null;
    this.currentUrl = null;
    this.init();
  }

  async init() {
    this.loadVersion();
    await this.detectCurrentPage();
    this.setupTabListeners();

    $('#bindCard').on('click', () => this.bindCard());
    $('#registerAccount').on('click', () => this.registerAccount());
    $('#generateCards').on('click', () => this.generateCards());
    $('#clearCardOutput').on('click', () => this.clearCardOutput());

    await this.loadSavedSettings();

    $('#binSelect').on('change', (event) => {
      const value = event.target.value;
      console.log('🔄 BIN选择变更，新值:', value);
      this.saveSettings('selectedBin', value);
    });

    $('#customBinInput').on('input', (event) => this.validateAndSaveCustomBin(event.target.value));
    $('#quantitySelect').on('change', (event) => this.saveSettings('selectedQuantity', event.target.value));
    $('#sessionEndpoint').on('input', (event) => this.handleSessionEndpointInput(event.target.value));
    $('#tmpmailUsername').on('input', (event) => this.saveSettings('tmpmailUsername', event.target.value.trim()));
    $('#tmpmailPassword').on('input', (event) => this.saveSettings('tmpmailPassword', event.target.value));

    this.addContactInfo();
    await this.extractAndDisplaySessionToken();
    this.setupSessionTokenCopy();
  }

  setupTabListeners() {
    chrome.tabs.onUpdated.addListener((tabId, changeInfo) => {
      if (tabId !== this.currentTabId) {
        return;
      }

      if (changeInfo.url) {
        console.log('检测到页面URL变化:', changeInfo.url);
        this.detectCurrentPage();
        this.extractAndDisplaySessionToken();
      }

      if (changeInfo.status === 'loading') {
        console.log('页面开始加载...');
        this.detectCurrentPage();
      }

      if (changeInfo.status === 'complete') {
        console.log('页面加载完成，重新检测状态');
        setTimeout(() => {
          this.detectCurrentPage();
          this.extractAndDisplaySessionToken();
        }, 300);
      }
    });

    chrome.tabs.onActivated.addListener((activeInfo) => {
      console.log('标签页切换:', activeInfo.tabId);
      this.currentTabId = activeInfo.tabId;
      this.detectCurrentPage();
      this.extractAndDisplaySessionToken();
    });
  }

  loadVersion() {
    const manifest = chrome.runtime.getManifest();
    $('#versionNumber').text(manifest.version);
  }

  async detectCurrentPage(retryCount = 0) {
    try {
      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
      if (!tab?.id) {
        this.updatePageStatus('unknown', '无法获取页面信息');
        return;
      }

      this.currentTabId = tab.id;
      this.currentUrl = tab.url;

      const [{ result } = {}] = await chrome.scripting.executeScript({
        target: { tabId: tab.id },
        func: () => ({
          title: document.title,
          href: window.location.href,
          hostname: window.location.hostname,
          readyState: document.readyState,
        }),
      });

      if (!result) {
        this.updatePageStatus('unknown', '检测失败');
        return;
      }

      const { title, href, hostname, readyState } = result;
      const normalizedTitle = (title || '').toLowerCase();
      const normalizedHost = (hostname || '').toLowerCase();
      const isDocumentReady = readyState === 'complete';
      const titleMissing = !title || title.trim() === '' || title === href;
      const shouldRetry = titleMissing && !isDocumentReady && retryCount < 3;
      let pageType = 'unknown';

      const isAugmentBilling = normalizedHost === 'billing.augmentcode.com';
      const isAugmentOther = normalizedHost.includes('augmentcode.com') && !isAugmentBilling;
      const isStripeCheckout = normalizedHost === 'checkout.stripe.com';
      const isCursorDomain = normalizedHost.includes('cursor.com');
      const looksLikeAugment = normalizedTitle.includes('augment code');
      const looksLikeCursor = normalizedTitle.includes('cursor');
      const logContext = `URL: ${href}, Title: ${title}`;

      if (isAugmentBilling && looksLikeAugment) {
        pageType = 'augment_bind';
        console.log(`✅ 检测到 Augment 绑卡页面 - ${logContext}`);
      } else if (isAugmentBilling && shouldRetry) {
        console.log(`⏳ Augment绑卡页面title未加载，等待重试... (${retryCount + 1}/3)`);
        setTimeout(() => this.detectCurrentPage(retryCount + 1), 500);
        pageType = 'augment_bind';
      } else if (isAugmentOther) {
        pageType = 'augment_other';
        console.log(`✅ 检测到 Augment 其他页面 - ${logContext}`);
      } else if (isStripeCheckout && looksLikeCursor) {
        pageType = 'cursor_bind';
        console.log(`✅ 检测到 Cursor 绑卡页面 - ${logContext}`);
      } else if (isStripeCheckout && shouldRetry) {
        console.log(`⏳ Cursor绑卡页面title未加载，等待重试... (${retryCount + 1}/3)`);
        setTimeout(() => this.detectCurrentPage(retryCount + 1), 500);
        pageType = 'cursor_bind';
      } else if (isCursorDomain) {
        pageType = 'cursor_other';
        console.log(`✅ 检测到 Cursor 其他页面 - ${logContext}`);
      } else {
        console.log(`❌ 未识别的页面类型 - ${logContext}`);
      }

      this.updatePageStatus(pageType, href);
    } catch (error) {
      console.error('页面检测失败:', error);
      this.updatePageStatus('unknown', '检测出错');
    }
  }

  updatePageStatus(pageType, url) {
    const statusEl = $('#pageStatus');
    const iconEl = statusEl.find('.status-icon');
    const textEl = statusEl.find('.status-text');

    statusEl.removeClass('cursor_bind cursor_other augment_bind augment_other unknown detecting');

    switch (pageType) {
      case 'cursor_bind':
        statusEl.addClass('cursor_bind');
        iconEl.html('<span class="check-icon"></span>');
        textEl.text('Cursor 绑卡页');
        break;
      case 'cursor_other':
        statusEl.addClass('cursor_other');
        iconEl.html('<span class="check-icon"></span>');
        textEl.text('Cursor');
        break;
      case 'augment_bind':
        statusEl.addClass('augment_bind');
        iconEl.html('<span class="check-icon"></span>');
        textEl.text('Augment 绑卡页');
        break;
      case 'augment_other':
        statusEl.addClass('augment_other');
        iconEl.html('<span class="check-icon"></span>');
        textEl.text('Augment');
        break;
      default:
        statusEl.addClass('unknown');
        iconEl.html('<span class="cross-icon"></span>');
        textEl.text('暂不支持该页面');
        break;
    }

    this.toggleSessionTokenVisibility(pageType);
  }

  toggleSessionTokenVisibility(pageType) {
    const container = $('.session-token-box');
    if (pageType === 'unknown') {
      container.hide();
    } else {
      container.show();
    }
  }

  addContactInfo() {
    const container = $('.contact-info');
    if (container.length === 0) {
      return;
    }

    const label = $('<span class="contact-label">交流群：</span>');
    const groupId = '1063272036';
    const link = $('<a class="contact-value"></a>')
      .text('🐧神秘组织（点击跳转加入）')
      .attr('href', `mqqapi://card/show_pslcard?src_type=internal&version=1&uin=${groupId}&card_type=group&source=qrcode`)
      .attr('target', '_blank')
      .attr('title', `QQ群：${groupId}`);

    container.append(label).append(link);
  }

  async saveSettings(key, value) {
    try {
      await chrome.storage.local.set({ [key]: value });
      console.log(`💾 保存${key}: ${value}`);
      const verification = await chrome.storage.local.get([key]);
      if (verification[key] === value) {
        console.log(`✅ 验证成功：${key} = ${verification[key]}`);
      } else {
        console.error(`❌ 验证失败：期望 ${value}，实际 ${verification[key]}`);
      }
    } catch (error) {
      console.error(`❌ 保存${key}失败:`, error);
    }
  }

  async loadSavedSettings() {
    try {
      const settings = await chrome.storage.local.get([
        'selectedBin',
        'customBin',
        'selectedQuantity',
        'savedCardOutput',
        'sessionEndpoint',
        'tmpmailUsername',
        'tmpmailPassword',
        'lastTmpmailMailbox',
      ]);

      console.log('=== 存储数据调试 ===');
      console.log('完整存储数据:', settings);
      console.log('selectedBin值:', settings.selectedBin);
      console.log('selectedBin类型:', typeof settings.selectedBin);

      let selectedBin = settings.selectedBin;
      if (!selectedBin) {
        selectedBin = $('#binSelect option:not([disabled]):first').val();
        await this.saveSettings('selectedBin', selectedBin);
        console.log('✅ 首次使用，保存默认BIN:', selectedBin);
      } else {
        console.log('✅ 加载已保存的BIN:', selectedBin);
      }

      $('#binSelect').val(selectedBin);
      const appliedValue = $('#binSelect').val();
      console.log('设置后的实际值:', appliedValue);
      if (appliedValue !== selectedBin) {
        console.error('⚠️ 警告：设置值失败！期望值:', selectedBin, '实际值:', appliedValue);
      }

      if (settings.customBin) {
        $('#customBinInput').val(settings.customBin);
        console.log('加载已保存的自定义BIN:', settings.customBin);
      }

      $('#quantitySelect').val(settings.selectedQuantity || '10');

      if (settings.savedCardOutput) {
        $('#cardOutput').val(settings.savedCardOutput);
        console.log('已恢复之前生成的卡号数据');
      }

      const endpoint = settings.sessionEndpoint || DEFAULT_SESSION_ENDPOINT;
      $('#sessionEndpoint').val(endpoint);
      if (!settings.sessionEndpoint) {
        await this.saveSettings('sessionEndpoint', endpoint);
      }

      $('#tmpmailUsername').val(settings.tmpmailUsername || 'bigtian');
      $('#tmpmailPassword').val(settings.tmpmailPassword || 'djx1314520..');
      this.updateTmpmailResult(settings.lastTmpmailMailbox || null);

      console.log('✅ 设置已加载完成');
      console.log('==================');
      this.updateClearButtonVisibility();
    } catch (error) {
      console.error('❌ 加载设置失败:', error);
      const fallbackBin = $('#binSelect option:not([disabled]):first').val();
      $('#binSelect').val(fallbackBin);
      $('#quantitySelect').val('10');
      await this.saveSettings('selectedBin', fallbackBin);
    }
  }

  async validateAndSaveCustomBin(input) {
    const numeric = input.replace(/\D/g, '');
    if (numeric !== input) {
      $('#customBinInput').val(numeric);
    }
    await this.saveSettings('customBin', numeric);
  }

  async handleSessionEndpointInput(value) {
    const trimmed = (value || '').trim();
    const sanitized = trimmed.endsWith('/') ? trimmed.slice(0, -1) : trimmed;
    $('#sessionEndpoint').val(sanitized || DEFAULT_SESSION_ENDPOINT);
    await this.saveSettings('sessionEndpoint', sanitized || DEFAULT_SESSION_ENDPOINT);
  }

  getSelectedBin() {
    return $('#customBinInput').val().trim() || $('#binSelect').val();
  }

  getSelectedQuantity() {
    return parseInt($('#quantitySelect').val(), 10) || 10;
  }

  generateCards() {
    try {
      const bin = this.getSelectedBin();
      const quantity = this.getSelectedQuantity();
      const cards = [];
      const failedIndexes = [];

      for (let index = 0; index < quantity; index += 1) {
        try {
          cards.push(generateCardInfo(bin));
        } catch (error) {
          if (error.message.includes('BIN校验失败')) {
            const message = `生成失败: ${error.message}\n\n请检查BIN是否正确。`;
            $('#cardOutput').val(message);
            this.saveSettings('savedCardOutput', message);
            this.updateClearButtonVisibility();
            return;
          }
          failedIndexes.push(index + 1);
        }
      }

      if (cards.length === 0) {
        const message = '生成失败：请检查BIN设置';
        $('#cardOutput').val(message);
        this.saveSettings('savedCardOutput', message);
        this.updateClearButtonVisibility();
        return;
      }

      const timestamp = new Date().toLocaleString('zh-CN');
      const cardBrand = cards[0].cardBrand || 'Unknown';
      let output = `=== 生成时间: ${timestamp} ===\n`;
      output += `BIN前缀: ${bin}\n`;
      output += `卡品牌: ${cardBrand}\n`;
      output += `成功生成: ${cards.length}/${quantity} 个卡号\n`;
      if (failedIndexes.length > 0) {
        output += `失败序号: ${failedIndexes.join(', ')}\n`;
      }
      output += '\n';

      cards.forEach((card) => {
        const compactNumber = card.cardNumber.replace(/\s/g, '');
        output += `${compactNumber}|${card.expiryDate}|${card.cvc}\n`;
      });

      $('#cardOutput').val(output);
      this.saveSettings('savedCardOutput', output);
      this.updateClearButtonVisibility();
      console.log(`✅ 生成完成: ${cards.length}/${quantity} 个卡号`);
    } catch (error) {
      console.error('生成卡号失败:', error);
      const message = `生成失败: ${error.message}`;
      $('#cardOutput').val(message);
      this.saveSettings('savedCardOutput', message);
      this.updateClearButtonVisibility();
    }
  }

  generateCardData() {
    const selectedBin = this.getSelectedBin();
    const cardInfo = generateCardInfo(selectedBin);
    faker.locale = 'en';
    const state = faker.address.stateAbbr();

    return {
      cardNumber: cardInfo.cardNumber,
      expiryDate: cardInfo.expiryDate,
      cvc: cardInfo.cvc,
      fullName: faker.name.findName(),
      country: 'US',
      province: state,
      city: faker.address.city(),
      address: faker.address.streetAddress(),
      addressLine2: faker.address.secondaryAddress(),
      postalCode: faker.address.zipCodeByState(state),
      cardBrand: cardInfo.cardBrand,
      selectedBin,
    };
  }

  async bindCard() {
    try {
      const cardData = this.generateCardData();
      this.sendSessionTokenToEndpoint();

      console.log('=== 生成的银行卡信息（一键绑卡） ' + new Date().toLocaleString('zh-CN') + ' ===');
      console.log(`💳 卡号: ${cardData.cardNumber} (BIN: ${cardData.selectedBin})`);
      console.log(`🏷️ 卡品牌: ${cardData.cardBrand}`);
      console.log(`📅 有效期: ${cardData.expiryDate}`);
      console.log(`🔒 CVC: ${cardData.cvc}`);
      console.log(`👤 姓名: ${cardData.fullName}`);
      console.log(`🌍 国家/州: ${cardData.country}/${cardData.province}`);
      console.log(`🏙️ 城市: ${cardData.city}`);
      console.log(`🏠 地址: ${cardData.address}, ${cardData.addressLine2}`);
      console.log(`📮 邮编: ${cardData.postalCode}`);
      console.log('================');

      const response = await chrome.runtime.sendMessage({
        action: 'bindCard',
        data: cardData,
      });

      if (response?.success) {
        console.log(`✅ ${response.message}`);
        console.log('一键绑卡流程将在后台继续执行');
      } else {
        console.error('一键绑卡失败:', response?.message || '未知错误');
      }
    } catch (error) {
      console.error('一键绑卡失败:', error);
      if (error.message?.includes('BIN校验失败')) {
        alert(`生成卡号失败:\n${error.message}\n\n请检查BIN是否正确。`);
      }
    }
  }

  async sendSessionTokenToEndpoint() {
    try {
      const { sessionToken, sessionEndpoint } = await chrome.storage.local.get([
        'sessionToken',
        'sessionEndpoint',
      ]);
      const token = sessionToken?.trim();
      if (!token) {
        console.warn('未能获取 Session Token，跳过回传');
        return;
      }

      const endpointBase = (sessionEndpoint || DEFAULT_SESSION_ENDPOINT).replace(/\/$/, '');
      const url = `${endpointBase}/api/import/session`;
      console.log('📨 正在回传 Session Token 到:', url);

      const response = await fetch(url, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ session: token }),
      });

      if (!response.ok) {
        const text = await response.text();
        console.error('Session 回传失败:', response.status, text.slice(0, 200));
        return;
      }

      console.log('✅ Session 回传成功');
    } catch (error) {
      console.error('Session 回传接口调用异常:', error);
    }
  }

  async registerAccount() {
    try {
      this.setRegisterButtonLoading(true);
      const cookieHeader = await this.ensureTmpmailSession();
      const domain = await this.fetchTmpmailDomain(cookieHeader);
      const mailbox = await this.createTmpmailMailbox(cookieHeader, domain);
      await chrome.storage.local.set({ lastTmpmailMailbox: mailbox });
      this.updateTmpmailResult(mailbox);
      const tabId = await this.getOrOpenAugmentRegisterTabId();
      await chrome.runtime.sendMessage({
        action: 'registerAccount',
        data: { email: mailbox.address, tabId },
      });
      console.log('✅ 邮箱已写入注册表单并尝试提交');
      this.monitorOnboardAndBind(tabId).catch((error) => console.error('绑卡监听失败:', error));
      this.pollMailboxForVerificationCode(mailbox, cookieHeader, tabId).catch((error) => {
        console.error('验证码获取失败:', error);
      });
    } catch (error) {
      console.error('一键注册失败:', error);
      alert(`一键注册失败：${error.message}`);
    } finally {
      this.setRegisterButtonLoading(false);
    }
  }

  setRegisterButtonLoading(isLoading) {
    const button = $('#registerAccount');
    button.prop('disabled', isLoading);
    button.text(isLoading ? '注册中...' : '一键注册');
  }

  async ensureTmpmailSession() {
    const cookies = await this.fetchTmpmailCookies();
    if (cookies.user_token && cookies.cf_clearance) {
      return this.formatCookieHeader(cookies);
    }
    await this.loginTmpmail();
    await sleep(500);
    const refreshed = await this.fetchTmpmailCookies();
    if (!refreshed.user_token) {
      throw new Error('登录 tmpmail 失败，未获取到 user_token');
    }
    if (!refreshed.cf_clearance) {
      console.warn('未获取到 cf_clearance，后续请求可能失败');
    }
    return this.formatCookieHeader(refreshed);
  }

  async loginTmpmail() {
    const username = $('#tmpmailUsername').val().trim();
    const password = $('#tmpmailPassword').val();
    if (!username || !password) {
      throw new Error('请先填写 tmpmail 账号与密码');
    }
    const response = await fetch(TMPMAIL_LOGIN_URL, {
      method: 'POST',
      headers: {
        ...TMPMAIL_HEADERS_BASE,
        Referer: `${TMPMAIL_BASE_URL}/user/login`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ username, password }),
      credentials: 'include',
    });
    if (!response.ok) {
      const text = await response.text();
      throw new Error(`登录失败 (${response.status}): ${text.slice(0, 120)}`);
    }
    let result;
    try {
      result = await response.json();
    } catch (error) {
      throw new Error('登录接口返回非JSON数据');
    }
    if (result?.success === false) {
      throw new Error(result?.message || '登录失败');
    }
  }

  async fetchTmpmailCookies() {
    const cookies = await chrome.cookies.getAll({ url: TMPMAIL_BASE_URL });
    const map = {};
    cookies.forEach((cookie) => {
      map[cookie.name] = cookie.value;
    });
    return map;
  }

  formatCookieHeader(cookieMap) {
    return Object.entries(cookieMap)
      .filter(([, value]) => value)
      .map(([name, value]) => `${name}=${value}`)
      .join('; ');
  }

  async openAugmentRegisterPage() {
    const tab = await new Promise((resolve, reject) => {
      chrome.tabs.create({ url: AUGMENT_REGISTER_URL, active: true }, (newTab) => {
        const error = chrome.runtime.lastError;
        if (error || !newTab?.id) {
          reject(new Error(error?.message || '无法打开 Augment 注册页面'));
        } else {
          resolve(newTab);
        }
      });
    });
    await this.waitForTabComplete(tab.id);
    return tab.id;
  }

  async getOrOpenAugmentRegisterTabId() {
    const [activeTab] = await chrome.tabs.query({ active: true, currentWindow: true });
    if (activeTab?.url?.startsWith('https://login.augmentcode.com/')) {
      return activeTab.id;
    }
    return this.openAugmentRegisterPage();
  }

  waitForTabComplete(tabId, timeout = 30000) {
    return new Promise((resolve, reject) => {
      let resolved = false;
      const timer = setTimeout(() => {
        if (!resolved) {
          chrome.tabs.onUpdated.removeListener(listener);
          reject(new Error('Augment 页面加载超时'));
        }
      }, timeout);

      const listener = (updatedId, changeInfo) => {
        if (updatedId === tabId && changeInfo.status === 'complete') {
          resolved = true;
          clearTimeout(timer);
          chrome.tabs.onUpdated.removeListener(listener);
          resolve();
        }
      };

      chrome.tabs.onUpdated.addListener(listener);
    });
  }

  async monitorOnboardAndBind(tabId) {
    let resolved = false;
    const timeout = setTimeout(() => {
      if (!resolved) {
        chrome.tabs.onUpdated.removeListener(listener);
      }
    }, 300000);

    const listener = (updatedId, changeInfo, tab) => {
      if (updatedId === tabId && changeInfo.status === 'complete' && tab?.url?.startsWith('https://app.augmentcode.com/onboard')) {
        resolved = true;
        clearTimeout(timeout);
        chrome.tabs.onUpdated.removeListener(listener);
        this.bindCard().catch((error) => console.error('自动绑卡失败:', error));
      }
    };

    chrome.tabs.onUpdated.addListener(listener);
  }

  async pollMailboxForVerificationCode(mailbox, cookieHeader, tabId) {
    const maxAttempts = 30;
    const intervalMs = 4000;
    let lastCheckedMailId = null;
    for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
      try {
        const mails = await this.fetchMailboxMails(mailbox.id, cookieHeader);
        if (mails.length > 0) {
          const latestMail = mails[0];
          if (latestMail.id !== lastCheckedMailId) {
            lastCheckedMailId = latestMail.id;
            const detail = await this.fetchMailDetail(latestMail.id, cookieHeader);
            const content = detail?.text_content || detail?.html_content || '';
            const code = this.extractVerificationCode(content);
            if (code) {
              await chrome.runtime.sendMessage({
                action: 'fillVerificationCode',
                data: { code, tabId },
              });
              console.log('✅ 已自动填入验证码:', code);
              return;
            }
          }
        }
      } catch (error) {
        console.error('轮询邮箱失败:', error);
      }
      await sleep(intervalMs);
    }
    console.warn('验证码轮询超时，未能自动完成验证');
  }

  async fetchMailboxMails(mailboxId, cookieHeader) {
    const response = await fetch(TMPMAIL_MAILS_URL(mailboxId), {
      method: 'GET',
      headers: this.buildTmpmailHeaders(cookieHeader),
    });
    if (!response.ok) {
      const text = await response.text();
      throw new Error(`获取邮件列表失败 (${response.status}): ${text.slice(0, 120)}`);
    }
    let result;
    try {
      result = await response.json();
    } catch (error) {
      throw new Error('邮件列表接口返回非JSON数据');
    }
    return Array.isArray(result?.mails) ? result.mails : [];
  }

  async fetchMailDetail(mailId, cookieHeader) {
    const response = await fetch(TMPMAIL_MAIL_DETAIL_URL(mailId), {
      method: 'GET',
      headers: this.buildTmpmailHeaders(cookieHeader),
    });
    if (!response.ok) {
      const text = await response.text();
      throw new Error(`获取邮件详情失败 (${response.status}): ${text.slice(0, 120)}`);
    }
    return response.json();
  }

  extractVerificationCode(content) {
    if (!content) return null;
    const htmlMatch = content.match(/verification code is:\s*<b>(\d{4,8})<\/b>/i);
    if (htmlMatch) {
      return htmlMatch[1];
    }
    const textMatch = content.match(/verification code is:\s*(\d{4,8})/i);
    return textMatch ? textMatch[1] : null;
  }

  buildTmpmailHeaders(cookieHeader, extra = {}) {
    return {
      ...TMPMAIL_HEADERS_BASE,
      Cookie: cookieHeader,
      ...extra,
    };
  }

  async fetchTmpmailDomain(cookieHeader) {
    const response = await fetch(TMPMAIL_DOMAIN_URL, {
      method: 'GET',
      headers: this.buildTmpmailHeaders(cookieHeader),
    });
    if (!response.ok) {
      const text = await response.text();
      throw new Error(`获取域名失败 (${response.status}): ${text.slice(0, 120)}`);
    }
    let payload;
    try {
      payload = await response.json();
    } catch (error) {
      throw new Error('域名接口返回非JSON数据');
    }
    const domainList = this.normalizeDomainList(payload).filter((domain) => !domain.endsWith('.icu'));
    if (domainList.length === 0) {
      throw new Error('没有可用的域名');
    }
    const index = Math.floor(Math.random() * domainList.length);
    return domainList[index];
  }

  normalizeDomainList(payload) {
    const list = Array.isArray(payload)
      ? payload
      : Array.isArray(payload?.domains)
        ? payload.domains
        : Array.isArray(payload?.data)
          ? payload.data
          : [];
    return list
      .map((item) => {
        if (!item) return null;
        if (typeof item === 'string') return item.trim();
        if (typeof item === 'object') {
          return item.domain || item.name || item.value || '';
        }
        return null;
      })
      .filter((domain) => typeof domain === 'string' && domain.trim().length > 0)
      .map((domain) => domain.toLowerCase());
  }

  async createTmpmailMailbox(cookieHeader, domain) {
    const response = await fetch(TMPMAIL_MAILBOX_URL, {
      method: 'POST',
      headers: this.buildTmpmailHeaders(cookieHeader, {
        'content-type': 'application/json',
        origin: `${TMPMAIL_BASE_URL}`,
      }),
      body: JSON.stringify({ username: '', domain, expiry_days: 7 }),
    });
    if (!response.ok) {
      const text = await response.text();
      throw new Error(`创建邮箱失败 (${response.status}): ${text.slice(0, 120)}`);
    }
    let result;
    try {
      result = await response.json();
    } catch (error) {
      throw new Error('邮箱创建接口返回非JSON数据');
    }
    if (!result?.success || !result?.mailbox?.address) {
      throw new Error(result?.message || '邮箱创建失败（未知原因）');
    }
    return {
      address: result.mailbox.address,
      quickAccessUrl: result.quick_access_url,
      domain: result.mailbox.domain,
      id: result.mailbox.id,
      expiresAt: result.mailbox.expires_at,
    };
  }

  updateTmpmailResult(mailbox) {
    const emailEl = $('#tmpmailEmail');
    const linkEl = $('#tmpmailQuickLink');
    if (mailbox?.address) {
      emailEl.text(mailbox.address);
      if (mailbox.quickAccessUrl) {
        linkEl.attr('href', mailbox.quickAccessUrl);
        linkEl.removeAttr('hidden');
      } else {
        linkEl.attr('hidden', true);
      }
    } else {
      emailEl.text('未生成');
      linkEl.attr('hidden', true);
    }
  }

  async clearCardOutput() {
    $('#cardOutput').val('');
    await this.saveSettings('savedCardOutput', '');
    this.updateClearButtonVisibility();
    console.log('已清空卡号输出');
  }

  updateClearButtonVisibility() {
    const content = $('#cardOutput').val() || '';
    const hasContent = content.trim() !== '';
    if (hasContent) {
      $('#clearCardOutput').addClass('show');
    } else {
      $('#clearCardOutput').removeClass('show');
    }
  }

  async extractAndDisplaySessionToken() {
    try {
      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
      if (!tab?.id) {
        this.updateSessionTokenDisplay(null, 'unknown');
        return;
      }

      const targetUrl = tab.url || '';
      const hostname = new URL(targetUrl).hostname.toLowerCase();
      const isCursor = hostname.includes('cursor.com');
      const isAugment = hostname.includes('augmentcode.com');

      if (!isCursor && !isAugment) {
        this.updateSessionTokenDisplay(null, 'unknown');
        return;
      }

      const tokenType = isCursor ? 'cursor' : 'augment';
      let token = null;

      if (tokenType === 'cursor') {
        try {
          const cookie = await chrome.cookies.get({ url: targetUrl, name: 'WorkosCursorSessionToken' });
          if (cookie) {
            token = cookie.value;
          }
        } catch (error) {
          console.error('获取 Cursor cookie 失败:', error);
        }
      } else {
        try {
          const cookie = await chrome.cookies.get({ url: 'https://auth.augmentcode.com', name: 'session' });
          if (cookie) {
            token = cookie.value;
          }
        } catch (error) {
          console.error('获取 Augment cookie 失败:', error);
        }
      }

      this.updateSessionTokenDisplay(token, tokenType);
      if (token) {
        await this.saveSettings('sessionToken', token);
        await this.saveSettings('sessionTokenType', tokenType);
        console.log(`✅ 成功提取 ${tokenType === 'cursor' ? 'Cursor' : 'Augment'} Session Token`);
      } else {
        console.log(`未在 ${tokenType === 'cursor' ? 'Cursor' : 'Augment'} 页面检测到 Session Token`);
      }
    } catch (error) {
      console.error('提取 Session Token 失败:', error);
      this.updateSessionTokenDisplay(null, 'unknown');
    }
  }

  updateSessionTokenDisplay(token, tokenType) {
    const container = $('#sessionTokenValue');
    const textEl = container.find('.token-text');

    if (token) {
      textEl.text(token);
      container.removeClass('not-detected');
      const readableType = tokenType === 'cursor' ? 'Cursor' : tokenType === 'augment' ? 'Augment' : '';
      container.attr('title', `点击复制 ${readableType} Session Token`);
      container.data('token', token);
      container.data('pageType', tokenType);
    } else {
      if (tokenType === 'cursor' || tokenType === 'augment') {
        const readableType = tokenType === 'cursor' ? 'Cursor' : 'Augment';
        textEl.text(`未检测到 ${readableType} Token`);
      } else {
        textEl.text('未检测到');
      }
      container.addClass('not-detected');
      container.attr('title', '');
      container.removeData('token');
      container.removeData('pageType');
    }
  }

  setupSessionTokenCopy() {
    $('#sessionTokenValue').on('click', function handleCopy() {
      const container = $(this);
      const token = container.data('token');
      const pageType = container.data('pageType');
      if (!token) {
        return;
      }

      const readableType = pageType === 'cursor' ? 'Cursor' : pageType === 'augment' ? 'Augment' : '';

      navigator.clipboard
        .writeText(token)
        .then(() => {
          console.log(`✅ ${readableType} Session Token 已复制到剪贴板`);
          console.log(`Token 长度: ${token.length} 字符`);
          container.addClass('copied');
          setTimeout(() => container.removeClass('copied'), 1500);
        })
        .catch((error) => {
          console.error('复制失败:', error);
          try {
            const textarea = document.createElement('textarea');
            textarea.value = token;
            textarea.style.position = 'fixed';
            textarea.style.opacity = '0';
            document.body.appendChild(textarea);
            textarea.select();
            document.execCommand('copy');
            document.body.removeChild(textarea);
            console.log(`✅ ${readableType} Session Token 已复制到剪贴板（降级方案）`);
            console.log(`Token 长度: ${token.length} 字符`);
            container.addClass('copied');
            setTimeout(() => container.removeClass('copied'), 1500);
          } catch (fallbackError) {
            console.error('降级复制方案也失败:', fallbackError);
          }
        });
    });
  }
}

$(document).ready(() => {
  new AutoFillManager();
});
